/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
/**
 * Created by zhb on 2020/8/4
 */

import $ from 'jquery';
import Vue from 'vue';

import PwdForm from 'src/home/mod_launch/nav/change_pwd';

const MODIFY_PASSWD_URL = '/auth/v1/user';

import axios from 'axios';

// 修改密码弹窗
function _createPwdFormWindow () {
    return Vue.prototype.$modal(PwdForm, {
        title: _('首次登录修改密码'),
        closeable: false,
        autoDestroy: true,
        buttons: [{
            actionName: 'submit',
            text: _('确定')
        }]
    });
};

// 修改密码
function _updateUserPassword (userData, token, options) {
    let pwdFormWindow = _createPwdFormWindow();
    pwdFormWindow.open({
        reset: false,
        submit () {
            let json = pwdFormWindow.formRoot.getJsonValue();
            options = {
                ...options,
                pwdFormWindow
            };
            _ajaxSubmit(json, token, userData, options);
        }
    });
};

async function _ajaxSubmit (json, token, userData, options) {

    let {pwdFormWindow} = options;

    // TODO,需要统一成success，看了下接口返回，success和status都有
    // 统一加上csrf头部信息
    let secretURL = `${MODIFY_PASSWD_URL}/${userData.userId}/secret`;

    // axios.defaults.headers.common.access_token = token;
    axios.put(secretURL, {
        account: userData.username,
        oldPwd: userData.password,
        newPwd: json.newPassword
    }).then((data)=>{
        let {success, msg} = data.data;
        if (!success) {
            this.$showErr(msg || _('登录失败'));
            return;
        }

        // 执行成功回调
        if (typeof options.successCB === 'function') {
            options.successCB();
        }

        //修改密码完成后，需要重新登录
        Vue.prototype.$ok(_('修改成功，请重新登录'));

        pwdFormWindow.hide();
        window.location.reload();


        //清空密码
        /* eslint-disable */
        $('.uedc-ppkg-login_input[type="password"]').val('');
         // 修改完刷新验证码
         $('.uedc-ppkg-login_product-captcha-input').val('');
    })

    
// return this.$ok(_('修改密码成功'));
};

export default _updateUserPassword;



